package com.linln.admin.personMch.controller;

import com.california.pay.facade.TerminalManagerFacade;
import com.california.pay.result.CommonResult;
import com.linln.admin.core.constant.AdminConst;
import com.linln.admin.core.enums.ResultEnum;
import com.linln.admin.core.enums.StatusEnum;
import com.linln.admin.core.exception.ResultException;
import com.linln.admin.core.log.action.StatusAction;
import com.linln.admin.core.log.annotation.ActionLog;
import com.linln.admin.core.shiro.ShiroUtil;
import com.linln.admin.core.web.TimoExample;
import com.linln.admin.personMch.domain.PPayPersonMch;
import com.linln.admin.personMch.domain.PayOrder;
import com.linln.admin.personMch.service.PPayPersonMchService;
import com.linln.admin.personMch.validator.PPayPersonMchForm;
import com.linln.core.utils.FormBeanUtil;
import com.linln.core.utils.ResultVoUtil;
import com.linln.core.vo.ResultVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Reference;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 小懒虫
 * @date 2018/12/21
 */
@Controller
@RequestMapping("/pPayPersonMch")
public class PPayPersonMchController {

    @Autowired
    private PPayPersonMchService pPayPersonMchService;

    @Reference
    private TerminalManagerFacade terminalManagerFacade;
    /**
     * 列表页面
     * @param pageIndex 页码
     * @param pageSize 获取数据长度
     */
    @GetMapping("/index")
    @RequiresPermissions("/pPayPersonMch/index")
    public String index(Model model, PPayPersonMch pPayPersonMch,
            @RequestParam(value="page",defaultValue="1") int pageIndex,
            @RequestParam(value="size",defaultValue="10") int pageSize){

        // 创建匹配器，进行动态查询匹配

        // 获取商户个人渠道管理列表/*ExampleMatcher matcher = ExampleMatcher.matching().
        //				withMatcher("channel_mch_account", match -> match.contains()).
        //				withMatcher("channel_user_id", match -> match.contains());
        //*/
        //Example<PPayPersonMch> example = TimoExample.of(pPayPersonMch, matcher);
        Page<PPayPersonMch> list = pPayPersonMchService.getPageList(pPayPersonMch, pageIndex, pageSize);

        // 封装数据
        model.addAttribute("list",list.getContent());
        model.addAttribute("page",list);
        return "/personMch/pPayPersonMch/index";
    }

    @PostMapping("/logout")
    @ResponseBody
    public ResultVo dealFailed(Model model, PPayPersonMch pPayPersonMch){
        // 不允许操作超级管理员数据
        if (!ShiroUtil.getSubject().getId().equals(AdminConst.ADMIN_ID)) {
            throw new ResultException(ResultEnum.NO_ADMIN_AUTH);
        }
        CommonResult<?> result = terminalManagerFacade.terminalLogout(pPayPersonMch.getChannelUserId());
        if(result.isSuccess()){
            return ResultVoUtil.success("下线成功！");
        }else{
            return ResultVoUtil.error("下线失败："+result.getErrmsg());
        }
    }
    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("/pPayPersonMch/add")
    public String toAdd(){
        return "/personMch/pPayPersonMch/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("/pPayPersonMch/edit")
    public String toEdit(@PathVariable("id") String id, Model model){
        PPayPersonMch pPayPersonMch = pPayPersonMchService.getId(id);
        model.addAttribute("pPayPersonMch",pPayPersonMch);
        return "/personMch/pPayPersonMch/add";
    }

    /**
     * 保存添加/修改的数据
     * @param pPayPersonMchForm 表单验证对象
     */
    @PostMapping({"/add","/edit"})
    @RequiresPermissions({"/pPayPersonMch/add","/pPayPersonMch/edit"})
    @ResponseBody
    public ResultVo save(@Validated PPayPersonMchForm pPayPersonMchForm){

        // 将验证的数据复制给实体类
        PPayPersonMch pPayPersonMch = new PPayPersonMch();
        if(pPayPersonMchForm.getPersonMchId() != null){
            pPayPersonMch = pPayPersonMchService.getId(pPayPersonMchForm.getPersonMchId());
            pPayPersonMch = pPayPersonMchService.getByChannelUserId(pPayPersonMchForm.getChannelUserId());
            if (pPayPersonMch != null && !pPayPersonMch.getPersonMchId().equals(pPayPersonMchForm.getPersonMchId())) {
                throw new ResultException(ResultEnum.CHANEL_USER_ID_EXIST);
            }
        }else{
            pPayPersonMch = pPayPersonMchService.getByChannelUserId(pPayPersonMchForm.getChannelUserId());
            if (pPayPersonMch != null) {
                throw new ResultException(ResultEnum.CHANEL_USER_ID_EXIST);
            }
            pPayPersonMch = new PPayPersonMch();
        }
        String[] ignore = {"createTime","updateTime"};
        FormBeanUtil.copyProperties(pPayPersonMchForm, pPayPersonMch, ignore);
        // 保存数据
        pPayPersonMchService.save(pPayPersonMch);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("/pPayPersonMch/detail")
    public String toDetail(@PathVariable("id") String id, Model model){
        PPayPersonMch pPayPersonMch = pPayPersonMchService.getId(id);
        model.addAttribute("pPayPersonMch",pPayPersonMch);
        return "/personMch/pPayPersonMch/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @ResponseBody
    @ActionLog(name = "删除商户个人渠道", action = StatusAction.class)
    public ResultVo delete(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<String> idList) {
        try {
            // 获取状态StatusEnum对象
            StatusEnum statusEnum = StatusEnum.valueOf(param.toUpperCase());
            // 更新状态
            Integer count = pPayPersonMchService.deleteByIds(idList);
            if (count > 0) {
                return ResultVoUtil.success(statusEnum.getMessage() + "成功");
            } else {
                return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
            }
        } catch (IllegalArgumentException e) {
            throw new ResultException(ResultEnum.STATUS_ERROR);
        }
    }

}
